package com.example.aop;

import com.example.mapper.OperateLogMapper;
import com.example.pojo.Emp;
import com.example.pojo.EmpLoginLog;
import com.example.pojo.LoginInfo; // 新增导入LoginInfo类
import com.example.pojo.Result;
import lombok.extern.slf4j.Slf4j;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.time.LocalDateTime;

/**
 * loginLog 类的描述信息
 *
 * @author 12427
 * @since 2025/6/9 15:47
 */
@Slf4j
@Aspect//定义是切面
@Component
public class loginLog {
    @Autowired
    private OperateLogMapper operateLogMapper;

    @Around("execution(* com.example.controller.LoginController.Login(..))")
    public Object around(ProceedingJoinPoint jop) throws Throwable {
        // 开始时间
        long start = System.currentTimeMillis();

        Object proceed = jop.proceed();//源代码运行

        // 结束时间
        long end = System.currentTimeMillis();
        long count = end - start;
        EmpLoginLog empLogin = new EmpLoginLog();
        Object[] args = jop.getArgs();
        Emp emp = (Emp) args[0];
        String name = emp.getUsername();//姓名
        String password = emp.getPassword();//密码
        Integer id = emp.getId();//id
        // 处理返回结果
        Result loginResult = (Result) proceed;
        empLogin.setId(id);
        empLogin.setUsername(name);
        empLogin.setPassword(password);
        empLogin.setLoginTime(LocalDateTime.now());
        boolean isSuccess = loginResult.getCode().equals(1); // 1表示成功
        // 修改这里：处理LoginInfo对象而不是直接转换为String
        String jwtToken = null;
        if (isSuccess && loginResult.getData() != null) {
            Object data = loginResult.getData();
            if (data instanceof LoginInfo) {
                LoginInfo loginInfo = (LoginInfo) data;
                jwtToken = loginInfo.getToken(); // 从LoginInfo对象获取JWT
            } else {
                log.warn("登录成功但返回数据类型不是LoginInfo: {}", data.getClass());
            }
        }
        empLogin.setIsSuccess(isSuccess ? (short) 1 : (short) 0); // 修正判断逻辑
        empLogin.setJwt(jwtToken);
        empLogin.setCostTime(count);
        operateLogMapper.insertLogin(empLogin);
        return proceed;
    }
}